﻿using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Xml;
using System.Linq;
using System.Linq.Expressions;

namespace CommerceServerContrib.CodeGeneration.Test
{
    /// <summary>
    /// Summary description for XMLTest
    /// </summary>
    [TestClass]
    public class XMLTest
    {
        public XMLTest()
        {
            
        }

        [TestMethod]
        public void AddDependentAssemblyEntry()
        {
            var xmlFile = new XmlDocument();
            xmlFile.Load("SampleConfig.xml");
            // get the configuration element
            var configuration = xmlFile.SelectSingleNode("configuration");
            if (configuration != null)
            {
                var runtime = configuration.SelectSingleNode("runtime");
                if (runtime == null)
                {
                    runtime = xmlFile.CreateElement("runtime");
                    configuration.AppendChild(runtime);
                }

                XmlNamespaceManager manager = new XmlNamespaceManager(xmlFile.NameTable);
                manager.AddNamespace("x", "urn:schemas-microsoft-com:asm.v1");
                var assemblyBinding = runtime.SelectSingleNode("x:assemblyBinding", manager);
                if (assemblyBinding == null)
                {
                    assemblyBinding = xmlFile.CreateElement("assemblyBinding", "urn:schemas-microsoft-com:asm.v1");
                    runtime.AppendChild(assemblyBinding);
                }

                // Finally add dependent assembly element
                var dependentAssembly = xmlFile.CreateElement("dependentAssembly", "urn:schemas-microsoft-com:asm.v1");
                dependentAssembly.InnerXml = "<assemblyIdentity name=\"CommerceMessageManager\" publicKeyToken=\"null\" culture=\"en-US\" version=\"6.0.1.0\"/><codeBase href=\"bin\\CommerceMessageManager.dll\"/>";
                assemblyBinding.AppendChild(dependentAssembly);
                // Then I would save/
            }

            // now remove
            var namespaceManage = new XmlNamespaceManager(xmlFile.NameTable);
            namespaceManage.AddNamespace("x", "urn:schemas-microsoft-com:asm.v1");
            var r = xmlFile.SelectSingleNode("/configuration/runtime/x:assemblyBinding", namespaceManage);
            var csAssemblyEntry = r.SelectSingleNode("x:dependentAssembly/assemblyIdentity[@name='CommerceMessageManager']", namespaceManage);
            r.RemoveChild(csAssemblyEntry.ParentNode);
        } 
    }
}
